/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.EventData;
import edu.bsu.android.gtv.apps.bconnected.data.MonthData;
import edu.bsu.android.gtv.apps.bconnected.objects.Event;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.PersistentListFragment;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * A {@link ListFragment} showing a list of events based on the month selected.  The listfragment appears in the right hand column of the 
 * {@link EventMultiPaneActivity} after the user selects a month.  Once an item is selected, the {@link EventInfoActivity} activity
 * is started.
 * @author Kyle Parker, University Computing Services
 */
public class EventFragment extends PersistentListFragment {
    private static final String TAG = "EventFragment";
    
	private OnEventListener mEventListener = null;
    private EventAdapter mEventAdapter;
	private boolean persistentSelection = false;
    
    private ArrayList<Event> mEvents;
    private Activity mActivity;
    private int mMonthPosition = 0;

	public EventFragment() {
		this(false);
	}
	
	public EventFragment(boolean persistentSelection) {
		this.persistentSelection = persistentSelection;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
		setRetainInstance(true);
    }

	@Override
	public void onActivityCreated(Bundle state) {
		super.onActivityCreated(state);
		
		mActivity = getActivity();

        AnalyticsUtils.getInstance(mActivity).trackPageView("/Events");
		registerForContextMenu(getListView());
		restoreState(state);
		
		if (persistentSelection) {
			enablePersistentSelection();
		}
		
    	mEvents = new ArrayList<Event>();
    	mEventAdapter = new EventAdapter(mActivity, R.layout.list_item, mEvents);
        setListAdapter(this.mEventAdapter); 
    	setListShown(false);
        
        loadEvents();
	}
    
    /** {@inheritDoc} */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		if (mEventListener != null) {
			mEventListener.onEventSelected(mEventAdapter.getItem(position));
		}
    }

    /**
     * Method called by the ConnectionFragment to launch the activity and set the necessary values for the web service calls
     * @param position
     */
    public void startActivity(final int position) {
    	mMonthPosition = position;
    	
    	if (mActivity != null) {
    		loadEvents();
    	}
    }

    /**
     * Using a new thread, separate from the main activity, load the event information from the service handler
     */
    private void loadEvents() { 
        Runnable load = new Runnable(){
            public void run() {
            	try {
            		if (MonthData.getMonthCount() > 0) {
		    	        int monthID = MonthData.getMonth(mMonthPosition).getMonthID();
		    	        int year = MonthData.getMonth(mMonthPosition).getYear();
		    	        
		    	        EventData.initializeEvent(monthID, year, mActivity);
		
		                if (EventData.getEventCount() > 0) {
		                	mEvents = EventData.getEvents();
		                } else {
		                	mEvents = null;
		                }
            		}

            		mActivity.runOnUiThread(returnEvent);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };

        Thread thread = new Thread(null, load, "loadEvents");
        thread.start();
        
        if (mActivity != null) {
        	setListShown(false);
        }
    }
    
    /**
     * Add each event object from the service handler to the array adapter and set the visibility of the spinner to "gone"
     */
    private Runnable returnEvent = new Runnable(){
        public void run() {
        	if (mEventAdapter.getCount() > 0) {
        		mEventAdapter.clear();
        	}
        	
            if (mEvents != null && mEvents.size() > 0){
                for(int i = 0; i < mEvents.size(); i++)
                {
                	mEventAdapter.add(mEvents.get(i));
                }
                
                // If there are items, the list needs to enabled (or re-enabled in the event a blank list was loaded initially)
            	getListView().setEnabled(true);
            } else {
            	Event empty = new Event();
            	empty.setError(mActivity.getString(R.string.empty_event));
            	mEventAdapter.add(empty);
            	
            	// If there are no items returned, disable the list selection
            	getListView().setEnabled(false);
            }

            mEventAdapter.notifyDataSetChanged();
            setListShown(true);
        }
    };

    /**
     * EventAdapter used to populate the listview for the events
     */
    private class EventAdapter extends ArrayAdapter<Event> {
        private ArrayList<Event> items;

        public EventAdapter(Context context, int textViewResourceId, ArrayList<Event> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {                     	
            View view = convertView;
            
            if (view == null) {
            	view = LayoutInflater.from(mActivity).inflate(R.layout.list_item_event, null);
            } 
            
            Event event = items.get(position);    
            
            if (event != null) {
            	if (event.getError() != null) {
                	UIUtils.displayTextView(view, R.id.name, event.getError());
            	} else {        	
                	String eventDate = event.getBeginDate();

        	    	if (event.getEndDate().length() > 0 && !event.getEndDate().matches(event.getBeginDate())) {
        	    		eventDate = eventDate + " - " + event.getEndDate();
        	    	}  
        	    	
                	UIUtils.displayTextView(view, R.id.date, eventDate); 
                	UIUtils.displayTextView(view, R.id.name, event.getEventName());
                	UIUtils.displayTextView(view, R.id.category, event.getCalendarEventName()); 
            	} 
            }
            
            return view;
        }
    }
    
	public void setOnEventListener(OnEventListener listener) {
		this.mEventListener = listener;
	}	
	
	public interface OnEventListener {
		void onEventSelected(Event event);
	}
}
